<template>
  <UploadExcel :on-success="handleSuccess" />
</template>

<script>
import { reqAddEmployeeBatch } from '@/api/employees'
// const 嘿嘿 = 1
// console.log(嘿嘿)

// let 嘻嘻嘻 = 1
// 嘻嘻嘻 = 456
// console.log(嘻嘻嘻)

export default {
  name: 'Import',
  created() {
    console.log(this.$route.query.type)
  },
  methods: {
    handleSuccess({ header, results }) {
      console.log(header, results)

      if (this.$route.query.type === 'user') {
        // 批量导入员工
        this.handleAddEmployeeBatch(header, results)
      }
      if (this.$route.query.type === 'money') {
        // 批量导入工资
        console.log('这里可以调用导入工资的方法')
      }
      if (this.$route.query.type === 'social') {
        // 批量导入社保
        console.log('这里可以调用导入社保的方法')
      }

      // ...
    },
    async handleAddEmployeeBatch(header, results) {
      // 一个中文字段 可以 对应一个英文字段
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }

      const arr = []
      results.forEach(item => {
        const obj = {}
        console.log(item)
        for (const key in item) {
          // key 入职日期 姓名 工号 手机号 转正日期
          // userRelations[key] timeOfEntry username workNumber mobile correctionTime
          const englishKey = userRelations[key]
          // if (englishKey === 'timeOfEntry' || englishKey === 'correctionTime') {
          if (['timeOfEntry', 'correctionTime', 'birthday'].includes(englishKey)) {
            // 表示你这个是转正日期 或者 入职日期, 处理一下item[key]
            obj[englishKey] = this.formatExcelDate(item[key], '-')
          } else {
            obj[englishKey] = item[key]
          }
        }
        console.log(obj)
        arr.push(obj)
      })

      console.log(arr, 8978)

      const res = await reqAddEmployeeBatch(arr)
      console.log(res)
      this.$message.success('批量导入员工成功!!!')
      this.$router.push('/employees')
    },
    formatExcelDate(numb, format) {
      const time = new Date(numb * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
